//
//  SEGOrderPayViewController.m
//  ExcellentHome
//
//  Created by Chiang on 2017/12/25.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGOrderPayViewController.h"
#import "SEGOrderSeiverListCell.h"
#import "SEGOrderDetailManager.h"
#import "SEGOrderPayItemModel.h"
#import "SEGOrderPayListViewController.h"
#import "SEGWorkOrderPayListModel.h"

#define kCellIdentifier @"kCellIdentifier"
@interface SEGOrderPayViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSArray *materielsArray;//服务费用
@property(nonatomic, strong) NSArray *payServicesArray;//物料费用
@property(nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic,assign) CGFloat totalAmount;

@end

@implementation SEGOrderPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    _dataSourceArray = [NSMutableArray array];
    [self queryPayDetail];
}

- (void)setupUI {
    self.title = @"确认账单";
    [self showCustomNavigationBackButton];
    
    UIView *tipView = ({
        UIView *tipView = [[UIView alloc] init];
        tipView.backgroundColor = kColor_bg;
        
        UIImageView *icon = [[UIImageView alloc] init];
        icon.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_tips")];
        [tipView addSubview:icon];
        
        UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 60)];
        tipLabel.text = @"账单已经发送给您，请确认价钱是否正确，如果无误，请尽快支付";
        tipLabel.numberOfLines = 0;
        tipLabel.font = kFont_13;
        tipLabel.textColor = kColor_2;
        [tipView addSubview:tipLabel];
        
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(15);
            make.left.mas_equalTo(35);
            make.right.mas_equalTo(-15);
            make.bottom.mas_equalTo(-15);
        }];
        
        [icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(14);
            make.top.equalTo(tipLabel.mas_top).offset(2);
        }];
        [self.view addSubview:tipView];
        tipView;
    });
    [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.mas_equalTo(0);
    }];
    
    UIButton *submitButton = ({
        UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [submitButton setTitle:@"费用无误,立即支付" forState:UIControlStateNormal];
        [submitButton setTitleColor:kColor_W forState:UIControlStateNormal];
        submitButton.titleLabel.font = kFont_17;
        submitButton.backgroundColor = kColor_T;
        [submitButton setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [submitButton setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        [submitButton addTarget:self action:@selector(payToolViewClick) forControlEvents:UIControlEventTouchUpInside];
        submitButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, LYSafeAreaBottom(), 0);
        [self.view addSubview:submitButton];
        submitButton;
    });
    [submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(49 + LYSafeAreaBottom());
    }];
   
    self.tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = kColor_bg;
        [tableView registerClass:[SEGOrderSeiverListCell class] forCellReuseIdentifier:kCellIdentifier];
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.estimatedRowHeight = 40.0f;
        tableView.rowHeight = UITableViewAutomaticDimension;
        [self.view addSubview:tableView];
        tableView;
    });
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(tipView.mas_bottom);
        make.bottom.equalTo(submitButton.mas_top);
    }];
}

#pragma mark - NetWork Requests
/**
 获取支付详情
 */
- (void)queryPayDetail {
    NSDictionary* params = @{ @"serviceOrderId" : _serviceOrderId,
                              @"organId" : _organId };
    [SVProgressHUD show];
    __weak typeof(self) weakSelf = self;
    [[SEGOrderDetailManager sharedManager] queryPayDetail:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (isSuccessed) {
            NSDictionary * dataDic = result[@"data"];
            NSArray *materielsArray = dataDic[@"materiels"] ? : @[];
            NSArray *payServicesArray = dataDic[@"payServices"] ? :@[];
            [weakSelf.dataSourceArray removeAllObjects];
            [weakSelf.dataSourceArray addObject:[weakSelf handelData:payServicesArray isMateriels:NO]];
            [weakSelf.dataSourceArray addObject:[weakSelf handelData:materielsArray isMateriels:YES]];
            weakSelf.totalAmount = [dataDic[@"totalFee"] floatValue]/100;
            weakSelf.tableView.tableFooterView = [weakSelf totalFeeView:weakSelf.totalAmount];
            [weakSelf.tableView reloadData];
        } else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        }
    }];
}

/**
 将嵌套的数组处理成单层的对象数组
 @param dataArray 需要处理的嵌套数组
 @param isMateriels 是否是物料数据
 @return 处理好的模型数组
 */
- (NSArray<SEGOrderPayItemModel*> *)handelData:(NSArray *)dataArray  isMateriels:(BOOL)isMateriels {
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
    for (NSDictionary *subDic in dataArray) {
        NSString *catalogName = subDic[@"catalogName"];
        // [bugfix 27654] 有偿列表type为0的时候展示其他类
        if ([ValueToString(subDic[@"type"]) intValue] == 0) {
            catalogName = @"其他类";
        }
        NSString *key = isMateriels ? @"goodsList" : @"serviceList";
        for (NSDictionary *goodListItem in subDic[key]) {
            SEGOrderPayItemModel *itemModel = [[SEGOrderPayItemModel alloc] init];
            itemModel.catalogName = catalogName;
            itemModel.itemName = goodListItem[isMateriels ? @"goodsName" : @"serviceName"];
            itemModel.itemModel = goodListItem[isMateriels ? @"goodsModel": @"model"];
            itemModel.itemBrand = goodListItem[@"goodsBrand"];
            itemModel.useCount = goodListItem[@"useCount"];
            itemModel.price = goodListItem[@"price"];
            itemModel.unit = goodListItem[@"unit"];
            itemModel.type = [subDic[@"type"] integerValue];
            itemModel.verificationType = [goodListItem[@"verificationType"] integerValue];
            [resultArray addObject:itemModel];
        }
    }
    return resultArray;
}

/**
 获取支付列表
 */
- (void)getPayMethodList {
    __weak typeof(self) weakSelf = self;
    NSDictionary* params = @{ @"serviceOrderId" : self.serviceOrderId,
                              @"organId" : self.organId,
                              @"payBzCode" : @"APP"
    };
    [SVProgressHUD show];
    [[SEGOrderDetailManager sharedManager] getNewPayMethodList:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (isSuccessed) {
            
            NSArray *payModelDicArray = result[@"data"][@"methods"];
            NSMutableArray<SEGWorkOrderPayListModel*> *payModels = [NSMutableArray array];
            if ([payModelDicArray isKindOfClass:[NSArray class]]) {
                [payModelDicArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    SEGWorkOrderPayListModel *payModel = [SEGWorkOrderPayListModel yy_modelWithDictionary:obj];
                    [payModels addObject:payModel];
                }];
            }
            
            // 4.8.0跳转新的支付列表控制器
            SEGOrderPayListViewController *payListVC = [[SEGOrderPayListViewController alloc] init];
            payListVC.dataSource = payModels;
            payListVC.amount = weakSelf.totalAmount;
            payListVC.trackId = weakSelf.trackId;
            payListVC.serviceOrderId = weakSelf.serviceOrderId;
            payListVC.organId = weakSelf.organId;
            payListVC.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:payListVC animated:YES];
        } else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        }
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataSourceArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_dataSourceArray[section] count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGOrderSeiverListCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];
    cell.row = indexPath.row;
    [cell updateWithModel:_dataSourceArray[indexPath.section][indexPath.row]];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return [_dataSourceArray[section] count] == 0 ? 0.1 : 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if ([_dataSourceArray[section] count] == 0) {
        return nil;
    }
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 44)];
    header.backgroundColor = kColor_W;
    
    UIImageView *iconImageView = [[UIImageView alloc] init];
    iconImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(section == 0 ? @"icon_Labor_fee" : @"icon_material_fee")];
    [header addSubview:iconImageView];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.equalTo(header);
    }];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 44)];
    titleLabel.textColor = kColor_1;
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    titleLabel.text = section == 0 ? @"人工费" : @"物料费";
    [header addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(iconImageView.mas_right).offset(5);
        make.centerY.equalTo(iconImageView);
    }];
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if ([_dataSourceArray[section] count] == 0) {
        return nil;
    }
    UIView *footer = [[UIView alloc] init];
    footer.backgroundColor = kColor_W;
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 2, LYScreenWidth(), 1)];
    lineView.backgroundColor = kColor_L2;
    [footer addSubview:lineView];
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return [_dataSourceArray[section] count] == 0 ? 0.1 : 3;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark - Private Method
/**
 点击支付
 */
- (void)payToolViewClick {
    [self getPayMethodList];
}

#pragma mark - UI Controls
- (UIView *)totalFeeView:(CGFloat)totalFee {
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 88)];
    footer.backgroundColor = [UIColor clearColor];
    
    UIView *labelBox = [[UIView alloc] init];
    labelBox.backgroundColor = kColor_W;
    [footer addSubview:labelBox];
    [labelBox mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(footer);
        make.height.mas_equalTo(44);
    }];
    
    UILabel *totalPriceLabel = [[UILabel alloc] init];
    totalPriceLabel.backgroundColor = kColor_W;
    NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:@"总计："];
    [attributedString addAttributes:@{
                                      NSFontAttributeName : kFont_17,
                                      NSForegroundColorAttributeName : kColor_1
                                      }
                              range:NSMakeRange(0, attributedString.length)];
    NSMutableAttributedString *priceString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f元", totalFee]];
    [priceString addAttributes:@{
                                 NSFontAttributeName : [UIFont boldSystemFontOfSize:17],
                                 NSForegroundColorAttributeName : kColor_S1
                                 }
                              range:NSMakeRange(0, priceString.length)];
    [attributedString appendAttributedString:priceString];
    totalPriceLabel.attributedText = attributedString;
    [labelBox addSubview:totalPriceLabel];
    [totalPriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(labelBox).offset(-15);
        make.top.bottom.equalTo(labelBox);
    }];
    
    UIImageView *decorateImageView = [[UIImageView alloc] init];
    decorateImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"bg_border")];
    decorateImageView.contentMode = UIViewContentModeScaleAspectFill;
    [footer addSubview:decorateImageView];
    [decorateImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(labelBox.mas_bottom);
        make.left.right.equalTo(footer);
        make.height.mas_equalTo(4);
    }];
    
    return footer;
}

@end
